package smtp;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.InitialDirContext;

public class DNS {

	private static final String MX_ATTRIB = "MX";
	private static final String ADDR_ATTRIB = "A";
	private static String[] MX_ATTRIBS = { MX_ATTRIB };
	private static String[] ADDR_ATTRIBS = { ADDR_ATTRIB };

	private InitialDirContext idc;

	public void DNSLookup() {
		Properties env = new Properties();
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
		try {
			idc = new InitialDirContext(env);
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public List<String> getMXServers(String domain) {

		List<String> servers = new ArrayList<String>();
		Attributes attrs;
		try {
			attrs = idc.getAttributes(domain, MX_ATTRIBS);
			Attribute attr = attrs.get(MX_ATTRIB);
			if (attr != null) {
				for (int i = 0; i < attr.size(); i++) {
					String mxAttr = (String) attr.get(i);
					String[] parts = mxAttr.split(" ");
					// Split off the priority, and take the last field
					servers.add(parts[parts.length - 1]);
				}
			}
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		for (String string : servers) {
			System.out.println(string);
		}

		return servers;
	}

	public List<String> getIPAddresses(String hostname) {

		List<String> ipAddresses = new ArrayList<String>();
		Attributes attrs;
		try {
			attrs = idc.getAttributes(hostname, ADDR_ATTRIBS);

			Attribute attr = attrs.get(ADDR_ATTRIB);
			if (attr != null) {
				for (int i = 0; i < attr.size(); i++) {
					ipAddresses.add((String) attr.get(i));
				}
			}
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		for (String string : ipAddresses) {
			System.out.println(string);
		}

		return ipAddresses;
	}

}
